#include <pthread.h>
#include "Socket.hpp"
#include "Server.hpp"
#include "Protocol.hpp"
#include "Calculator.hpp"
#include "Daemon.hpp"
using namespace SocketModule;

void Usage(const std::string &name)
{
    std::cout << "usage: " << name << " + port" << std::endl;
}

int main(int argc, char* args[])
{
    if (argc != 2)
    {
        Usage(args[0]);
        exit(USAGE_ERROR);
    }
    in_port_t port = std::stoi(args[1]);

    // 日志切换为文件策略
    USE_FILE_STRATEGY();

    // 设置为守护进程
    if(Daemon(0, 0) == -1)
    {
        LOG(LogLevel::FATAL) << "Deamon: 设置守护进程失败! " << strerror(errno);
        exit(DAEMON_ERROR);
    }
    // daemon(0, 0)

    // 顶层
    Calculator calculator;

    // 协议层
    Protocol protocol([&calculator](const Request& request){
        return calculator.Calculate(request);
    });

    // 服务器层
    Server server(port, [&protocol](const std::shared_ptr<TCPConnectSocket>& socket){
        protocol.ServerService(socket);
    });
    server.Run();

    return 0;
}